#include <STC15F2K60S2.H>
#include"onewire.h"
typedef unsigned char uchar;
typedef unsigned int uint;

#define SEGOFF 0xff

uchar segTable[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
uchar segDisp[9] = {SEGOFF,SEGOFF,SEGOFF,SEGOFF,SEGOFF,SEGOFF,SEGOFF,SEGOFF,SEGOFF};

uchar keyCount;
uchar lastTrg;
uchar cont;

uint tempCount;
uchar tempConfig;
uchar tempResolu = 12;
uint tempPeriod = 750;
uint tempValue;

uchar i;

void Timer2Init(void)		//1����@11.0592MHz
{
	AUXR |= 0x04;			//��ʱ��ʱ��1Tģʽ
	T2L = 0xCD;				//���ö�ʱ��ʼֵ
	T2H = 0xD4;				//���ö�ʱ��ʼֵ
	AUXR |= 0x10;			//��ʱ��2��ʼ��ʱ
	IE2 |= 0x04;			//ʹ�ܶ�ʱ��2�ж�
}


void keyRead()
{
  uchar trg,cur;
  
  cur = (P3|0xF0)^0xFF;
  trg = cur & (cont ^ cur);
  cont = cur;
  
  if((lastTrg & (trg ^ lastTrg)) && cur)
  {
    if(cur & 0x08) //s4
    {
      tempConfig -=32;
      //���üĴ�����ֵ0x7F->0x5F->0x3F->0x1F
      if(tempConfig<0x1F) tempConfig = 0x7F;
      //�ı�ֱ���
      SetConfig(tempConfig);
      if(--tempResolu == 8) tempResolu = 12;
      //����ֱ��ʶ�Ӧ����
      //12 -- 11 -- 10 -- 9
      //750 -- 375 -- 185.5 -- 93.75 ÿ��/2
      tempPeriod = (750 >> (12-tempResolu)) +0.5;
      //������֮���ȡ�¶�
      tempCount = tempPeriod +1;
      
      if(tempResolu>=10) segDisp[1]=segTable[tempResolu/10];
      else segDisp[1]=SEGOFF;
      
      segDisp[2]=segTable[tempResolu%10];
      
    }
  }
  lastTrg = trg;
  
}

void keyProc()
{
  if(keyCount >= 10)
  {
    keyCount = 0;
    keyRead();
  }
}

void segProc()
{
  
  static uchar segBit = 1;
  
  P0 = 0x00,P2 = 0xC0,P2 = 0x00;
  P0 = segDisp[segBit],P2 = 0xE0,P2 = 0x00;
  P0 = 1 << (segBit-1),P2 = 0xC0,P2 = 0x00;
  
  if(++segBit == 9) segBit = 1;

}

void tempProc()
{
  if(tempCount >= tempPeriod)
  {
    tempCount = 0;
    tempValue = TempRead() *100+0.5;

  }
    if(tempValue>1000) segDisp[5] = segTable[tempValue/1000%10];
    else segDisp[5] = SEGOFF;
    
    segDisp[6] = segTable[tempValue/100%10]&0x7F;
    segDisp[7] = segTable[tempValue/10%10];
    segDisp[8] = segTable[tempValue%10]; 
}

void AllInit()
{
  P0 = 0xFF,P2 = 0x80,P2 = 0x00;
  P0 = 0x00,P2 = 0xA0,P2 = 0x00;
  for(i=0;i<100;i++) tempValue = TempRead() *100+0.5;
  segDisp[1] = segTable[tempResolu/10];
  segDisp[2] = segTable[tempResolu%10];
  Timer2Init();
  //�����ж�Ҫ��סѽ������
  EA = 1;
}
int main()
{
  AllInit();
  for(;;)
  {
    keyProc();
    tempProc();
  }
}

void Timer2_Isr(void) interrupt 12
{
  ++keyCount;
  ++tempCount;
  segProc(); //�����ж�ˢ��ʹ���������ʾ�¶�
}
